package com.wangsd.common.exception;

import com.wangsd.common.controller.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ResponseStatus(code = HttpStatus.OK)
    @ExceptionHandler(Exception.class)
    public Object handleException(Exception ex, HttpServletRequest request) {
        if (ex instanceof BusinessException) {
            log.error("业务异常：", ex);
            BusinessException businessException = (BusinessException) ex;
            AjaxResult data = AjaxResult.builder().code(businessException.getErrCode()).data(businessException.getErrMessage()).build();
            return data;
        } else {
            log.error("通用异常：", ex);
            AjaxResult data = AjaxResult.builder().code(BusinessErrorEnum.UNKNOWN_ERROR.getErrCode()).data("通用异常").build();
            return data;
        }
    }
}
